import { reactive } from "vue"

type ActionFunction = (...args: any[]) => any
type ActionsObject = Record<string, ActionFunction>

type IStore<T extends object, U extends ActionsObject> = T & U
type IStoreFactory<T extends object, U extends ActionsObject> = () => {
  state: T
  actions: U
}

export default function createStore<T extends object, U extends ActionsObject>(
  factory: IStoreFactory<T, U>
): () => IStore<T, U> {
  const { state, actions: originalActions } = factory()
  const reactiveState = reactive(state) as T

  // 创建带缓存的actions
  const cachedActions = {} as U

  ;(Object.keys(originalActions) as Array<keyof U>).forEach(
    <K extends keyof U>(key: K) => {
      const action = originalActions[key]

      const cacheMap = new Map<string, ReturnType<U[K]>>()

      // 修复类型断言语法错误
      const wrappedAction = (...args: Parameters<U[K]>): ReturnType<U[K]> => {
        const cacheKey = JSON.stringify(args)

        if (cacheMap.has(cacheKey)) {
          return cacheMap.get(cacheKey)!
        }

        const result = action.apply(reactiveState, args)

        if (result instanceof Promise) {
          const promise = result.finally(() => {
            // 可以在这里添加缓存清理逻辑
          })
          cacheMap.set(cacheKey, promise as ReturnType<U[K]>)
          return promise as ReturnType<U[K]>
        }

        cacheMap.set(cacheKey, result)
        return result
      }

      cachedActions[key] = wrappedAction as U[K]
    }
  )

  return () => ({
    ...reactiveState,
    ...cachedActions
  })
}
